package com.example.crm.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.crm.entity.SalesTarget;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 销售目标Mapper接口
 */
@Mapper
public interface SalesTargetMapper extends BaseMapper<SalesTarget> {
    
    /**
     * 查询指定用户在指定周期内的销售目标
     * @param userId 用户ID
     * @param targetPeriod 目标周期
     * @return 销售目标列表
     */
    @Select("SELECT t.*, u.real_name as user_name, c.real_name as creator_name FROM crm_sales_target t " +
            "LEFT JOIN sys_user u ON t.user_id = u.id " +
            "LEFT JOIN sys_user c ON t.creator_id = c.id " +
            "WHERE t.user_id = #{userId} AND t.target_period = #{targetPeriod} AND t.deleted = 0")
    List<SalesTarget> selectUserTargetsByPeriod(@Param("userId") Long userId, @Param("targetPeriod") String targetPeriod);
    
    /**
     * 查询指定团队在指定周期内的销售目标
     * @param teamId 团队ID
     * @param targetPeriod 目标周期
     * @return 销售目标列表
     */
    @Select("SELECT t.*, tm.name as team_name, u.real_name as creator_name FROM crm_sales_target t " +
            "LEFT JOIN crm_sales_team tm ON t.team_id = tm.id " +
            "LEFT JOIN sys_user u ON t.creator_id = u.id " +
            "WHERE t.team_id = #{teamId} AND t.target_period = #{targetPeriod} AND t.deleted = 0")
    List<SalesTarget> selectTeamTargetsByPeriod(@Param("teamId") Long teamId, @Param("targetPeriod") String targetPeriod);
    
    /**
     * 统计用户目标完成情况
     * @param userId 用户ID
     * @return 统计结果（按周期分组）
     */
    @Select("SELECT target_period, SUM(target_value) as total_target, SUM(actual_value) as total_actual " +
            "FROM crm_sales_target WHERE user_id = #{userId} AND deleted = 0 " +
            "GROUP BY target_period ORDER BY target_period DESC")
    List<Map<String, Object>> statisticsUserTargets(@Param("userId") Long userId);
} 